package com.jike.jkgame;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.jike.jkgame.exception.EncodingException;
import com.jike.jkgame.exception.NetworkErrorException;
import com.jike.jkgame.network.MessageFactory;
import com.jike.jkgame.network.NetworkUtilis;
import com.jike.jkgame.network.ServerConfig;

public class UserInitActivity extends Activity implements OnClickListener {
	
	private EditText mNameEt;
	private EditText mGeneralEt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.user_init_layout);
		
		mNameEt = (EditText) findViewById(R.id.et_nickname);
		mGeneralEt = (EditText) findViewById(R.id.et_general);
		
		findViewById(R.id.btn_init).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_init:
			InitUserTask task = new InitUserTask();
			task.execute(mNameEt.getText().toString(), mGeneralEt.getText().toString());
			break;

		default:
			break;
		}
	}
	
	class InitUserTask extends AsyncTask<String, Integer, Integer> {

		@Override
		protected Integer doInBackground(String... params) {
			if (params == null || params.length < 2) {
				return null;
			}
			
			JSONObject req = MessageFactory.createIniteUseroReqMessage(params[0], Integer.valueOf(params[1]));
			
			try {
				String response = NetworkUtilis.getHttpString(ServerConfig.get().getGameServer(), req);
				
				JSONObject json = new JSONObject(response);
				
				return json.optInt("opcode", -1);
				
			} catch (NetworkErrorException e) {
				e.printStackTrace();
			} catch (EncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			if (result != null && result == 0) {
				setResult(1);
				finish();
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		
		
	}
	
	

}
